<?php
require_once("{$CfgPara->root}/class/user_operate.class.php");
require_once("{$CfgPara->root}/class/make_img_name.class.php");
require_once("{$CfgPara->root}/class/do_edit_img.func.php");
require_once("{$CfgPara->root}/class/mysql.func.php");

/**
 * work 作品数据模型
 *
 * @version 1.0
 * @author Human
 */
class work_m
{
    //$type 列表类型 0管理作品 1热门 2关注 3最新 4专题已审核的 5专题未审核的 6我的推荐 7我的收藏 8个人作品（发布的） 9个人作品（草稿）
    /**
     * 列表类型 管理作品
     */
    const ListManage = 0;
    /**
     * 列表类型 热门
     */
    const ListHot = 1;
    /**
     * 列表类型 关注
     */
    const ListUp = 2;
    /**
     * 列表类型 最新
     */
    const ListNew = 3;
    /**
     * 列表类型 专题下已审核的作品 默认按加入时间排序
     */
    const ListTopicOK = 4;
    /**
     * 列表类型 专题下尚未审核的作品
     */
    const ListTopicWait = 5;
    /**
     * 列表类型 我的推荐
     */
    const ListMyUp = 6;
    /**
     * 列表类型 我的收藏
     */
    const ListMyCollect = 7;
    /**
     * 列表类型 个人作品（发布的）
     */
    const ListUserWorksRelease = 8;
    /**
     * 列表类型 个人作品（草稿）
     */
    const ListUserWorksDraft = 9;
    /**
     * 列表类型 个人某个本领中的作品
     */
    const ListUserField = 10;
    /**
     * 列表类型 投稿专题时显示的个人作品表
     */
    const ListUserForTopic = 11;
    /**
     * 列表类型 本领中加入作品时显示的个人作品表
     */
    const ListUserForField = 12;
    /**
     * 列表类型 本领中的作品管理、排序
     */
    const ListUserFieldForOrder = 13;
    /**
     * 列表类型 专题下已审核的作品 按热门排序
     */
    const ListTopicOKHot = 14;
    /**
     * 列表类型 专题下已审核的作品 按推荐排序
     */
    const ListTopicOKRecommend = 15;
    /**
     * 列表类型 24小时热门
     */
    const ListHot101 = 101;
    /**
     * 列表类型 昨日热门
     */
    const ListHot102 = 102;
    /**
     * 列表类型 本周热门
     */
    const ListHot103 = 103;
    /**
     * 列表类型 本月热门
     */
    const ListHot104 = 104;
    /**
     * 列表子类型 当前仅作品 按最新排列
     */
    const ListSubOrder_New = 201;
    /**
     * 列表子类型 当前仅作品 按推荐排列
     */
    const ListSubOrder_Rec = 202;
    /**
     * 列表子类型 当前仅作品 按热度排列
     */
    const ListSubOrder_Hot = 203;

    /**
     * 作品数量类型 全部作品
     */
    const CountAllWork = 0;
    /**
     * 作品数量类型 我的作品
     */
    const CountMyWork = 1;
    /**
     * 作品数量类型 我的推荐
     */
    const CountMyUp = 2;
    /**
     * 作品数量类型 我的收藏
     */
    const CountMyCollect = 3;
    /**
     * 作品数量类型 专题下已审核的作品
     */
    const CountWorkForTopicOK = 4;
    /**
     * 作品数量类型 专题下待审核的作品
     */
    const CountWorkForTopicWait = 5;
    /**
     * 作品数量类型 个人作品（发布的）
     */
    const CountUserWorksRelease = 8;
    /**
     * 作品数量类型 个人作品（草稿）
     */
    const CountUserWorksDraft = 9;
    /**
     * 作品数量类型 热门
     */
    const CountHot = 101;
    /**
     * 作品数量类型 关注
     */
    const CountFollow = 102;
    /**
     * 作品数量类型 最新
     */
    const CountNew = 103;
    /**
     * 日期时间的判断正则表达式 YYYY-MM-DD HH:MM:SS
     */
    const PregDateTime =
        '/^\d{4}-(?:0\d|1[0-2])-(?:[0-2]\d|3[01])( (?:[01]\d|2[0-3])\:[0-5]\d\:[0-5]\d)?$/';

    /**
     * @var int 获取的列表的项目数 获取作品列表时 如果设置了计算总数
     * 则为作品总数量，如果没设置为-1 如果计算时错误为-2
     */
    public $work_list_count;

    /**
     * @var int 设置列表排序 获取作品列表时，需要的排序方式
     * 支持按时间201、推荐数202、热度排序203 参考列表类型常量
     */
    public $work_list_sub_order = 0;

    public function __construct($dbPara = null)
    {
        if ($dbPara != null) {
            db_connect($dbPara);
        }
    }


    /**
     * 获取作品列表时 如果设置了计算总数 成功返回数量，
     * 错误返回错误信息
     * @param mixed $type 数量类型 参考类中的常量
     * @param mixed $id 查询Id 例如我的作品数量 为用户Id
     * @return mixed
     */
    public function work_count($type, $id, $hotType = 0)
    {
        if ($type == work_m::CountAllWork) {
            $sql_str = "SELECT Count(*) FROM `works`";
        } elseif ($type == work_m::CountMyWork) //管理作品 草稿与发布的均显示
        {
            $sql_str = "SELECT `WorksCount` + `WorksDraftCount` FROM `users` WHERE `Id` = {$id}";
        } elseif ($type == work_m::CountMyUp || $type == work_m::CountMyCollect) {
            if ($type == work_m::CountMyUp) {
                $name = 'RecommendCount';
            } else {
                $name = 'CollectOtherCount';
            }
            $sql_str = "SELECT `{$name}` FROM `users` WHERE `Id` = {$id}";
        } elseif ($type == work_m::CountWorkForTopicOK || $type == work_m::CountWorkForTopicWait) {
            if ($type == work_m::CountMyWork) {
                $name = 'WorksCount';
            } else {
                $name = 'WaitCheckCount';
            }
            $sql_str = "SELECT `{$name}` FROM `topic` WHERE Id= {$id}";
        } elseif ($type == work_m::CountUserWorksRelease || $type == work_m::CountUserWorksDraft) {
            if ($type == work_m::CountUserWorksRelease) $fname = 'WorksCount';
            else $fname = 'WorksDraftCount';
            $sql_str = "SELECT `{$fname}` FROM `users` WHERE `Id` = {$id}";
        } elseif ($type == work_m::CountNew) {
            $sql_str = "SELECT Count(1) FROM `works` WHERE `State` = 1";
        } else {
            return '错误的作品数量统计类型';
        }
        $result = db_query($sql_str);
        if ($result !== false) {
            if ($row = $result->fetch_array()) {
                return $row[0];
            } else {
                return '作品数量统计无结果';
            }
        } else {
            return db_error();
        }
    }

    /**
     * 获取作品图片 返回文件名数组
     */
    public function work_imgs($img_text)
    {
        $workImg_temp = explode(";", $img_text);
        $workImg_count = count($workImg_temp);
        if ($workImg_count > 9) {
            for ($i = 10; $i <= $workImg_count; $i++) {
                unset($workImg_temp[$i]);
            }
        }
        if ($workImg_count > 0) {
            return $workImg_temp;
        } else {
            return false;
        }
    }

    /**
     * 作品列表 成功返回作品对象数组 错误返回错误信息
     * @param int $type 参考本类中的列表类型常量
     * @param int $id 管理作品:当前用户id 热门:0 关注:0 最新:0 专题:专题Id 我的推荐:当前用户id
     * @param int $page 当前页索引
     * @param int $page_size 每页条目数
     * @param string $search 搜索的内容
     * @param bool $count 是否同时计算总数
     * @return mixed
     */
    function work_list($type, $id, $page, $page_size, $search = null, $count = false)
    {
        if (!is_numeric($type) || !is_numeric($id) || !is_numeric($page) || !is_numeric($page_size)) {
            return '错误:作品列表查询信息错误';
        }
        $is_hot_order = false;
        $limit_offset = ($page - 1) * $page_size;//计算偏移量
        if ($search != null && is_string($search))  //加入全文检索语句
        {
            $search_text = urldecode($search);
            $search_text = db_escape($search_text);
            if (strlen($search_text) < 2) {
                return "搜索文本长度应大于1";
            }
            if ($search_text !== false) {
                //20170111 修改 搜索匹配的关键词都在Keyword中
                $search_sql = "AND MATCH (`works`.`Keyword`) AGAINST ('{$search_text}')";
            } else {
                $search_sql = '';
            }
        } else {
            $search_sql = '';
        }
        if ($count === true) //同时计算检索总数 而不受limit影响
        {
            $found_rows_sql = 'SQL_CALC_FOUND_ROWS';
        } else {
            $this->work_list_count = -1;
            $found_rows_sql = '';
        }
        if ($type == work_m::ListManage) //管理作品(我的作品)
        {
            // 20170129 添加 当前对话为管理员登陆时，管理作品将显示所有作品
            if (isset($_SESSION['user_admin']) && $_SESSION['user_admin'] == 1 &&
                isset($_SESSION['user_level']) && $_SESSION['user_level'] >= 90
            ) {
                $sql_str = "SELECT {$found_rows_sql} `works`.* FROM `works`";
                if ($search_sql != '') {
                    $search_sql = str_replace('AND ', '', $search_sql);
                    $sql_str .= "WHERE {$search_sql} ";
                }
            } else {
                $sql_str = "SELECT {$found_rows_sql} `works`.* FROM `works` WHERE `Author` = {$id} {$search_sql} ";
            }
            //20170112 添加 按最新、推荐、热度的排序功能
            if ($this->work_list_sub_order == work_m::ListSubOrder_Hot) //按热度排列
            {
                $sql_str = $this->work_list_hot(work_m::ListHot101, $limit_offset, $page_size, 1, $id);
            } elseif ($this->work_list_sub_order == work_m::ListSubOrder_Rec) //按推荐排列
            {
                $sql_str .= "ORDER BY `works`.`UpCount` DESC ";
            } else //默认按最新排序
            {
                $sql_str .= "ORDER BY `works`.`ReleaseDt` DESC, `works`.`Id` DESC ";
            }
        } elseif ($type == work_m::ListHot ||     //当选择为热门时 默认为24小时内热门
            $type == work_m::ListHot101 ||  //24小时内热门
            $type == work_m::ListHot102 ||  //昨日热门
            $type == work_m::ListHot103 ||
            $type == work_m::ListHot104
        ) {
            $is_hot_order = true;
            $sql_str = $this->work_list_hot($type, $limit_offset, $page_size);
        } elseif ($type == work_m::ListTopicOKHot) {
            $sql_ex1 = ',`topic_works` '; //仅在专题中的作品
            $sql_ex2 = "AND `works`.`Id` = `topic_works`.`WorkId` AND `topic_works`.`TopicId` = {$id} ";
            $sql_str = "SELECT {$found_rows_sql} `works`.*,`users`.`Name` as UserName,
                               (`works`.`CommentCount`*`sys_hot_compute`.`CommentWeight`+ `works`.`UpCount`*`sys_hot_compute`.`UpWeight`) as HotPoint
                        FROM `works`,`sys_hot_compute`,`users` {$sql_ex1}
                        WHERE `works`.`Author` = `users`.`Id` AND `works`.`State` = 1 {$sql_ex2}
                        ORDER BY `HotPoint` DESC";
        } elseif ($type == work_m::ListUp)//关注 用户关注的作者的作品
        {
            if (isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id'])) {
                $sql_str = "SELECT {$found_rows_sql} `works`.*,`users`.`Name` as UserName FROM `works`,`user_follow`,`users`
                            WHERE `user_follow`.`FansId` = {$_SESSION['user_id']} 
                            AND `user_follow`.`UserId` = `works`.`Author` 
                            AND  `users`.`Id` = '{$_SESSION['user_id']}' 
                            AND `works`.`State` = 1 
                            ORDER BY `works`.`Id` DESC";
            } else //如果没有登陆 则返回一个空的关注列表
            {
                $result = array();
                return $result;
            }
        } elseif ($type == work_m::ListNew)//3最新
        {
            $sql_str = "SELECT {$found_rows_sql} `works`.*,`users`.`Name` as UserName FROM `works`,`users`
                            WHERE `works`.`Author` = `users`.`Id` AND `works`.`State` = 1 {$search_sql} 
                            ORDER BY `works`.`Id` DESC";
        } elseif ($type == work_m::ListTopicOK) //4专题已审核的
            $sql_str = "SELECT {$found_rows_sql} `works`.*,`users`.`Name` as UserName FROM `works`,`topic_works`,`users` WHERE `works`.`Id` = `topic_works`.`WorkId` AND `works`.`Author` = `users`.`Id` AND `topic_works`.`TopicId` = {$id} AND `topic_works`.`State` = 1 AND `works`.`State` = 1 ORDER BY `topic_works`.`CheckDt` DESC";
        elseif ($type == work_m::ListTopicWait) //5专题未审核的
            $sql_str = "SELECT {$found_rows_sql} `works`.* FROM `works`,`topic_works` WHERE `works`.`Id` = `topic_works`.`WorkId` AND `topic_works`.`TopicId` = '{$id}' AND `topic_works`.`State` = 0 AND `works`.`State` = 1 ORDER BY `topic_works`.`ReleaseDt` DESC";
        elseif ($type == work_m::ListMyUp) //6我的推荐
        {
            $sql_str = "SELECT {$found_rows_sql} `works`.* FROM `works`,`works_up` WHERE `works_up`.`UserId` = {$id} AND `works`.`Id` = `works_up`.`WorkId` {$search_sql}";
            //20170112 添加 按最新、推荐、热度的排序功能
            if ($this->work_list_sub_order == work_m::ListSubOrder_Hot) //按热度排列
            {
                $sql_str = $this->work_list_hot(work_m::ListHot101, $limit_offset, $page_size, 2, $id);
            } elseif ($this->work_list_sub_order == work_m::ListSubOrder_Rec) //按推荐排列
            {
                $sql_str .= "ORDER BY `works`.`UpCount` DESC ";
            } else //默认按最新排序
            {
                $sql_str .= "ORDER BY `works_up`.`UpDt` DESC ";
            }
        } elseif ($type == work_m::ListMyCollect)//我的收藏
        {
            $sql_str = "SELECT {$found_rows_sql} `works`.* 
                        FROM `works`,`user_collect` 
                        WHERE `works`.`Id` = `user_collect`.`CollectId` AND 
                              `user_collect`.`UserId` = {$id} AND `user_collect`.`Type` = 0 {$search_sql} ";
            //20170112 添加 按最新、推荐、热度的排序功能
            if ($this->work_list_sub_order == work_m::ListSubOrder_Hot) //按热度排列
            {
                $sql_str = $this->work_list_hot(work_m::ListHot101, $limit_offset, $page_size, 3, $id);
            } elseif ($this->work_list_sub_order == work_m::ListSubOrder_Rec) //按推荐排列
            {
                $sql_str .= "ORDER BY `works`.`UpCount` DESC ";
            } else //默认按最新排序
            {
                $sql_str .= "ORDER BY `user_collect`.`CollectDt` DESC ";
            }
        } elseif ($type == work_m::ListUserWorksRelease) //个人主页中的作品列表
        {
            $sql_str = "SELECT {$found_rows_sql} `works`.*, `users`.`Name` as UserName FROM `works`,`users`
                        WHERE `works`.`Author` = {$id} AND `works`.`State` = 1 AND `users`.`Id` = {$id} ";
            //20170113 添加 按最新、推荐、热度的排序功能
            if ($this->work_list_sub_order == work_m::ListSubOrder_Hot) //按热度排列
            {
                $sql_str = $this->work_list_hot(work_m::ListHot101, $limit_offset, $page_size, 1, $id);
            } elseif ($this->work_list_sub_order == work_m::ListSubOrder_Rec) //按推荐排列
            {
                $sql_str .= "ORDER BY `works`.`UpCount` DESC ";
            } else //默认按最新排序
            {
                $sql_str .= "ORDER BY `works`.`Id` DESC ";
            }
        } elseif ($type == work_m::ListUserWorksDraft ||
            $type == work_m::ListUserForTopic ||
            $type == work_m::ListUserForField
        ) {
            if ($type == work_m::ListUserWorksDraft) $state = 0;
            else $state = 1;
            $sql_str = "SELECT {$found_rows_sql} `works`.*, `users`.`Name` as UserName FROM `works`,`users`
                        WHERE `works`.`Author` = {$id} AND `works`.`State` = {$state} AND 
                              `users`.`Id` = {$id} {$search_sql} 
                        ORDER BY `works`.`Id` DESC";
        } // 20170428 新的本领下的作品列表已经在查询本领信息时直接获取
        elseif ($type == work_m::ListUserField ||
            $type == work_m::ListUserFieldForOrder
        )//本领下的作品列表
        {
            // 20170531 仅在需要的时候获取数量
            /*
            // 特殊处理 无论有没有设置$count 都输出数量
            // 获取本领下作品的数量
            $sql_str = "SELECT WorksCount FROM user_field WHERE `Id` = {$id}";
            $result = db_query($sql_str);
            if ($result === FALSE) return db_error();
            $this->work_list_count = 0;
            if ($count = $result->fetch_object())
            {
                $this->work_list_count = $count->WorksCount;
            }
            else
            {
                return '无法获取本领下的作品数量';
            }
            if ($this->work_list_count <= 0) return array();
            */
            $sql_str = "SELECT {$found_rows_sql} `works`.* FROM `user_field_works`, `works` 
                        WHERE `user_field_works`.`FieldId` = {$id} AND 
                              `user_field_works`.`WorkId` = `works`.`Id`";

        } elseif ($type == work_m::ListTopicOKRecommend) {
            $sql_str = "SELECT {$found_rows_sql} `works`.*, `users`.`Name` as UserName 
        	            FROM `works`,`users`,`topic_works` 
        	            WHERE `works`.`Author` = `users`.`Id` AND 
        	                  `works`.`Id` = `topic_works`.`WorkId` AND 
        	                  `topic_works`.`TopicId` = {$id} 
        	            ORDER BY `works`.`UpCount` DESC";
        } else
            return "错误:作品列表查询类型错误";
        if (!$is_hot_order) //热度的算法内部已经添加了页码的选择
        {
            $sql_str .= " LIMIT {$limit_offset},{$page_size}";
        }
        if ($sql_str == '') {
            return array(); //如果最终判断没有sql语句 返回空的列表数组
        }
        $result = db_query($sql_str);
        if ($result instanceof mysqli_result) {
            $fetch_result = db_fetch_list($result, $rows);
            if ($count === true && $is_hot_order === false) // 热度算法内部已经增加了计算列表的总量
            {
                $found_count = db_query('SELECT FOUND_ROWS()');
                if ($found_count !== false) {
                    $this->work_list_count = $found_count->fetch_array()[0];
                } else {
                    $this->work_list_count = -2;
                }
            }
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 获取查询热门作品列表的sql语句
     * @param int $type 热门类型
     * @param int $limit_offset 获取偏移量
     * @param int $limit_count 获取个数
     * @param int $condition 附加的条件 0无 1用户的作品 2用户推荐的作品 3用户收藏的作品
     * @param int $conditionId 附加的条件的相关id
     */
    function work_list_hot($type, $limit_offset, $limit_count, $condition = 0, $conditionId = 0)
    {
        // 附加条件用的 sql 0无 1用户的作品 2用户推荐的作品 3用户收藏的作品
        // 此类型的热度无需考虑时间问题，直接在works表中选择相应条件的作品后排序
        $sql_str = '';
        $hotPointSql = "works.*,(works.UpCount * sys_hot_compute.UpWeight +
                        works.CommentCount * sys_hot_compute.CommentWeight +
                        works.ViewCount) as HotPoint";
        if ($condition == 1) //1用户的作品
        {
            $sql_str = "SELECT {$hotPointSql} FROM works,sys_hot_compute 
                        WHERE works.Author = {$conditionId} 
                        ORDER BY HotPoint DESC";
            return $sql_str;
        } elseif ($condition == 2) //2用户推荐的作品
        {
            $sql_str = "SELECT {$hotPointSql} FROM works,works_up,sys_hot_compute 
                        WHERE works.Id = works_up.WorkId AND works_up.UserId = {$conditionId}
                        ORDER BY HotPoint DESC";
            return $sql_str;
        } elseif ($condition == 3) //3用户收藏的作品
        {
            $sql_str = "SELECT {$hotPointSql} FROM works,user_collect,sys_hot_compute 
                        WHERE user_collect.Type = 0 AND 
                              user_collect.UserId = {$conditionId} AND 
                              works.Id = user_collect.CollectId
                        ORDER BY HotPoint DESC";
            return $sql_str;
        }

        $sql_time2 = date('Y-m-d H:i:s');
        //计算不同的热度算法的时间跨度
        if ($type == work_m::ListHot ||
            $type == work_m::ListHot101 ||
            $type == work_m::ListHot102
        ) {
            $sql_tbl = 'works_hot_1';
            if ($type == work_m::ListHot102) {
                $sql_time1 = date('Y-m-d H:i:s', strtotime('-2 day'));
                $sql_time2 = date('Y-m-d H:i:s', strtotime('-1 day'));
            } else {
                $sql_time1 = date('Y-m-d H:i:s', strtotime('-1 day'));
            }
        } else {
            $sql_tbl = 'works_hot_2';
            if ($type == work_m::ListHot103) {
                $sql_time1 = date('Y-m-d H:i:s', strtotime('-7 day'));
            } else {
                $sql_time1 = date('Y-m-d H:i:s', strtotime('-30 day'));
            }
        }

        //首先计算排序并获取当前页的作品Id，以及热门作品总数
        $sql_str = "SELECT SQL_CALC_FOUND_ROWS {$sql_tbl}.WorkId as HotWorkId,
						   Count(CASE WHEN {$sql_tbl}.OpType = 1 THEN 1 ELSE NULL END) * sys_hot_compute.UpWeight +
						   Count(CASE WHEN {$sql_tbl}.OpType = 2 THEN 1 ELSE NULL END) * sys_hot_compute.CommentWeight +
						   Count(CASE WHEN {$sql_tbl}.OpType = 3 THEN 1 ELSE NULL END) as HotPoint
					FROM {$sql_tbl},sys_hot_compute
					WHERE sys_hot_compute.Id = 1 AND 
						  {$sql_tbl}.OpDt BETWEEN '{$sql_time1}' AND '{$sql_time2}' 
					GROUP By HotWorkId
					ORDER BY HotPoint DESC
					LIMIT {$limit_offset},{$limit_count}";
        //return $sql_str;
        $result_sql = db_query($sql_str);
        if ($result_sql === FALSE) {
            return db_error();
        }
        $this->work_list_count = -1;
        //查询先前记录热门作品总数
        $result_count = db_query('SELECT FOUND_ROWS()');
        if ($result_count !== false) {
            $this->work_list_count = $result_count->fetch_array()[0];
        } else {
            $this->work_list_count = -2;
        }
        if ($this->work_list_count <= 0) {
            return '';
        }
        $sql_str = '';
        //根据先前查询的作品Id 获取完整作品信息
        while ($row = $result_sql->fetch_object()) {
            $sql_str .= "SELECT * FROM `works` WHERE `Id` = {$row->HotWorkId} UNION ALL ";
        }
        if ($sql_str == '') {
            return $sql_str;
        };
        $sql_str = substr($sql_str, 0, strlen($sql_str) - 10); //查询语句删除掉最后的'UNION ALL '
        $sql_str = "SELECT t1.*,users.`Name` as UserName FROM (
						SELECT * FROM(
							{$sql_str}
						) as t2
					) as t1
					left outer join users
					ON t1.Author = users.Id ";
        return $sql_str;
    }

    function work_list_limit_offset(& $sql_str, $limit_offset, $limit_count)
    {
        $sql_str .= " LIMIT {$limit_offset},{$limit_count}";
    }

    /**
     * 作品评论列表 成功返回评论对象数组 错误返回错误信息
     * @param int $work_id 作品id
     * @param int $page 当前页
     * @param int $page_size 每页条目数
     * @param int $desc 是否倒序，1倒序
     */
    function work_comment_list($work_id, $page, $page_size, $desc = 0)
    {
        if (!is_numeric($work_id) || !is_numeric($page) || !is_numeric($page_size)) {
            return "错误:评论查询信息错误";
        }
        $limit_offset = ($page - 1) * $page_size;//计算偏移量
        $sql_str = "SELECT `works_comment`.*,date_format(`works_comment`.`CommentDt`,'%m.%d %H:%i') as CommentDt2, `users`.`Avatar`,`users`.`Name` as UserName FROM `works_comment`, `users` 
                    WHERE `works_comment`.`WorkId` = '{$work_id}' AND `users`.`Id` = `works_comment`.`UserId` 
                    ORDER BY `works_comment`.`Id` ";
        if ($desc == 1) {
            $sql_str .= 'DESC ';
        }
        $sql_str .= "LIMIT {$limit_offset},{$page_size}";
        $result = db_query($sql_str);
        if ($result instanceof mysqli_result) {
            $fetch_result = db_fetch_list($result, $rows);
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 获取单个评论信息 成功返回评论对象 错误返回错误信息
     * @param int $comment_id 评论Id
     */
    function comment_msg($comment_id)
    {
        if (!is_numeric($comment_id)) {
            return "错误:评论查询信息错误";
        }
        $sql_str = "SELECT `works_comment`.*,date_format(`works_comment`.`CommentDt`,'%m.%d %H:%i') as CommentDt2, `users`.`Avatar`,`users`.`Name` as UserName 
                    FROM `works_comment`, `users` 
                    WHERE `works_comment`.`Id` = '{$comment_id}' AND `users`.`Id` = `works_comment`.`UserId`";
        $result = db_query($sql_str);
        if ($result instanceof mysqli_result) {
            if ($msg = $result->fetch_object()) {
                return $msg;
            } else {
                return '获取评论信息失败';
            }
        } else {
            return db_error();
        }
    }

    /**
     * 评论的回复列表 成功返回评论对象数组 错误返回错误信息
     * @param int $comment_id 评论Id
     * @param int $view_type 查看类型 0精简 仅用户名和内容 1完整 像评论一样
     * @param int $findCount (引用)总回复数 错误为-1
     * @param int $limit 限制查询数量 0为不限制
     * @param int $desc 是否倒序，1倒序
     */
    function comment_reply_list($comment_id, $view_type, &$find_count, $limit = 0, $desc = 0)
    {
        if (!is_numeric($comment_id) || !is_numeric($limit)) {
            return "错误:评论回复查询信息错误";
        }
        if ($view_type == 0) //精简样式
        {
            $sql_str = "SELECT SQL_CALC_FOUND_ROWS `works_comment`.`Text`,`works_comment`.`AtUserName`,`users`.`Name` as UserName 
                        FROM `works_comment`, `users` 
                        WHERE `works_comment`.`ReplyId` = '{$comment_id}' AND `users`.`Id` = `works_comment`.`UserId` 
                        ORDER BY `works_comment`.`Id` ";
        } else {
            $sql_str = "SELECT SQL_CALC_FOUND_ROWS `works_comment`.*,date_format(`works_comment`.`CommentDt`,'%m.%d %H:%i') as CommentDt2, `users`.`Avatar`,`users`.`Name` as UserName 
                        FROM `works_comment`, `users` 
                        WHERE `works_comment`.`ReplyId` = '{$comment_id}' AND `users`.`Id` = `works_comment`.`UserId` 
                        ORDER BY `works_comment`.`Id` ";
        }
        if ($desc == 1) {
            $sql_str .= 'DESC ';
        }
        if ($limit > 0) {
            $sql_str .= "LIMIT {$limit}";
        }
        $result = db_query($sql_str);
        if ($result instanceof mysqli_result) {
            $found_count_result = db_query('SELECT FOUND_ROWS()');
            if ($found_count_result !== false) {
                $find_count = $found_count_result->fetch_array()[0];
            } else {
                $find_count = -1;
            }
            $fetch_result = db_fetch_list($result, $rows);
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 作品推荐 成功推荐返回1 取消推荐返回-1 错误返回错误信息
     * @param int $work_id 作品Id
     */
    function work_recommend($work_id, $from_topic = 0)
    {
        if (!is_numeric($work_id) || !is_numeric($from_topic) || $from_topic < 0) {
            return "错误:推荐信息错误";
        }
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return "请登录";
        }
        //确认当前作品存在 且已发布，草稿作品不能推荐
        $work_msg_result = db_query(
            "SELECT `State` FROM works 
                 WHERE `Id` = {$work_id} AND `State` = 1");
        if ($work_msg_result === false) {
            return db_rollback();
        }
        if ($work_msg_result->num_rows <= 0) //没有获得作品信息
        {
            return "错误:无法获取此作品信息,如果此作品为草稿,无法推荐";
        }

        //更新数据的类型 如果是添加则为+ 如果是取消推荐 则为-
        $update_type = '+';
        $result = 1;
        db_begin();
        $result1 = db_query("INSERT INTO `works_up` 
                                       SET `WorkId` = {$work_id},
                                           `UserId` = {$_SESSION['user_id']},
                                           `FromTopic` = {$from_topic}");
        if ($result1 !== true) {
            if (db_errno() === 1062)//已经推荐过 则删除掉推荐
            {
                $update_type = '-';
                $result = -1;
                //如果已推荐过 先查询此推荐的信息 提供后面使用
                $result_sele = db_query("SELECT * FROM `works_up` 
                                         WHERE `WorkId` = {$work_id} AND 
                                               `UserId` = {$_SESSION['user_id']}");
                if ($result_sele !== FALSE) {
                    if ($upMsg = $result_sele->fetch_object()) {

                    } else {
                        db_rollback();
                        return '获取相关推荐信息时失败';
                    }
                } else {
                    return db_rollback();
                }
                //再删除掉
                $result11 = db_query("DELETE FROM `works_up` 
                                      WHERE `WorkId` = {$work_id} AND 
                                            `UserId` = {$_SESSION['user_id']}");
                if ($result11 !== true) {
                    return db_rollback();
                }

                //删除掉上次推荐时间正负1秒内的热门统计 Limit1
                $date = new DateTime($upMsg->UpDt);
                $i = DateInterval::createFromDateString('-1 seconds');
                $date->add($i);
                $sql_time1 = $date->format('Y-m-d H:i:s');
                $i = DateInterval::createFromDateString('+2 seconds');
                $date->add($i);
                $sql_time2 = $date->format('Y-m-d H:i:s');
                $result11 = db_query("DELETE FROM `works_hot_1` 
                                      WHERE `WorkId` = {$work_id} AND 
                                            `OpType` = 1 AND 
                                            `OpDt` BETWEEN '{$sql_time1}' AND '{$sql_time2}' 
                                      LIMIT 1");
                if ($result11 !== true) {
                    return db_rollback();
                }
                $result11 = db_query("DELETE FROM `works_hot_2`
                                      WHERE `WorkId` = {$work_id} AND 
                                            `OpType` = 1 AND 
                                            `OpDt` BETWEEN '{$sql_time1}' AND '{$sql_time2}'
                                      LIMIT 1");
                if ($result11 !== true) {
                    return db_rollback();
                }
            } else {
                return db_rollback();
            }
        } else {
            //推荐信息插入成功 则插入热门统计表
            $result11 = db_query("INSERT INTO `works_hot_1` 
                                  SET `WorkId` = {$work_id},
                                      `OpType` = 1");
            if ($result11 !== true) {
                return db_rollback();
            }
            $result11 = db_query("INSERT INTO `works_hot_2` 
                                  SET `WorkId` = {$work_id},
                                      `OpType` = 1");
            if ($result11 !== true) {
                return db_rollback();
            }
        }

        //更新当前作品的推荐数
        $result2 = db_query("UPDATE `works` 
                             SET `UpCount` = `UpCount` {$update_type} 1 
                             WHERE `Id` = {$work_id}");
        if ($result2 !== true) {
            return db_rollback();
        }

        //更新当前作品在专题下获得的推荐数
        if ($result == 1 && $from_topic > 0) {
            //如果为推荐 且来自专题 则更新专题关于此作品的推荐数自加1
            $result_update = db_query("INSERT INTO `works_up_topic` 
                                       SET `WorkId` = {$work_id},
                                           `TopicId` = {$from_topic},
                                           `UpCount` = 1 
                                       ON DUPLICATE KEY 
                                       UPDATE `UpCount` = `UpCount` + 1");
            if ($result_update !== true) {
                return db_rollback();
            }

        } elseif (isset($upMsg->FromTopic) && is_numeric($upMsg->FromTopic) && $upMsg->FromTopic > 0) {
            //如果为取消推荐 且在删除前已查询到的来自专题信息
            //如果来自专题 则更新专题关于此作品的推荐数自减1
            $result_update = db_query("UPDATE `works_up_topic` 
                                       SET `UpCount` = `UpCount` - 1 
                                       WHERE `WorkId` = {$work_id} AND
                                             `TopicId` = {$upMsg->FromTopic} ");
            if ($result_update !== true) {
                return db_rollback();
            }
        }

        //更新作者获得的推荐数
        $result3 = db_query("UPDATE `users`,`works` SET `users`.`HeartCount` = `users`.`HeartCount` {$update_type} 1 
                             WHERE `users`.`Id` = `works`.`Author` AND `works`.`Id` = {$work_id}");
        if ($result3 !== true) {
            return db_rollback();
        }

        //更新推荐者的推荐别人作品数
        $result4 = db_query("UPDATE `users` SET `RecommendCount` = `RecommendCount` {$update_type} 1 
                                       WHERE `Id` = {$_SESSION['user_id']}");
        if ($result4 !== true) {
            return db_rollback();
        }


        $op = new user_operate();
        $result1 = $op->operate_save($op::WorkUp, $_SESSION['user_id'], $work_id);
        if ($result1 !== TRUE) {
            db_rollback();
            return $result1;
        }

        db_commit();
        return $result;
    }

    /**
     * 作品推荐人员列表 成功返回对象数组 错误返回错误信息
     * @param int $work_id 作品id
     * @param int $page 当前页
     * @param int $page_size 每页条目数
     */
    function work_recommend_list($work_id, $page, $page_size)
    {
        if (!is_numeric($work_id)) {
            return "错误:推荐信息错误";
        }
        $limit_offset = ($page - 1) * $page_size;//计算偏移量
        $result = db_query("SELECT `works_up`.*,`users`.`Name` as UserName 
                            FROM `works_up`,`users` 
                            WHERE `works_up`.`WorkId` = '{$work_id}' AND 
                                  `works_up`.`UserId` = `users`.`Id` 
                            ORDER BY `works_up`.`UpDt` DESC 
                            LIMIT {$limit_offset},{$page_size} ");
        if ($result !== false) {
            $fetch_result = db_fetch_list($result, $rows);
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 作品评论保存 成功返回当前作品评论数 评论数获取错误时返回'-1' 错误返回错误信息
     * @param int 作品Id
     * @param int 本评论回复的对象id 为0直接发表
     * @param string 评论的文本
     */
    function work_comment_save($work_id, $reply_id, $comment, $at_username)
    {
        if (!is_numeric($work_id) || !is_numeric($reply_id)) {
            return "错误:评论保存信息错误";
        }
        $c = urldecode($comment);
        $c = db_escape($c);
        //20170119 添加 评论需要回复@的用户名 当前仅在评论的详细页面中的灰色列表中的回复才有
        $at = urldecode($at_username);
        $at = db_escape($at);

        if (mb_strlen($c, 'utf8') > 135) {
            return "错误:提交的评论长度超过135字符";
        }
        if ($c !== false) {
            $work_msg_result = db_query(
                "SELECT `works`.`Author`,`works`.`CommentCount`
                 FROM works
                 WHERE `works`.`Id` = {$work_id} AND `works`.`State` = 1");
            if ($work_msg_result === false) return db_error();

            if ($work_msg_result->num_rows <= 0 ||
                !($work_msg = $work_msg_result->fetch_object())
            ) //没有获得作品信息
            {
                return "错误:无法获取此作品信息,如果此作品为草稿,无法评论";
            }
            db_begin();
            $result = db_query(
                "INSERT INTO `works_comment` SET 
                `WorkId` = '{$work_id}',
                `UserId` = '{$_SESSION['user_id']}',
                `ReplyId` = '{$reply_id}',
                `Text` = '{$c}',
                `AtUserName` = '{$at}'");
            if ($result !== true) return db_rollback();

            $comment_id = db_insert_id();
            $comment_count = (int)$work_msg->CommentCount + 1;

            //推送消息到作者
            $sql_str = "INSERT INTO `message_comment` 
                        SET `Type` = 1,`MsgIdFrom` = {$comment_id},`UserId`={$work_msg->Author}";
            $result = db_query($sql_str);
            if ($result !== true) return db_rollback();

            //20170119 添加 推送消息到回复的评论作者
            if ($reply_id > 0) //回复的id>0代表此条评论为回复信息
            {
                //获取回复的评论的评论信息
                $sql_str = "SELECT works_comment.UserId, users.Name as UserName
                            FROM works_comment,users 
                            WHERE works_comment.Id = {$reply_id} AND 
                                  works_comment.UserId = users.Id";
                $comment_msg_result = db_query($sql_str);
                if ($comment_msg_result === false) return db_rollback();
                if ($comment_msg_result->num_rows <= 0 ||
                    !($comment_msg = $comment_msg_result->fetch_object())
                ) //没有获得回复的对象
                {
                    db_rollback();
                    return "错误:无法获取回复的对象";
                }
                // 如果需要回复的评论作者不是作品作者 测试时可注释掉if
                //if ($comment_msg->UserId != $work_msg->Author)
                //{
                //推送消息到需要回复的评论的作者
                $sql_str = "INSERT INTO `message_comment` 
                                SET `Type` = 3,`MsgIdFrom` = {$comment_id},`UserId`={$comment_msg->UserId}";
                $result = db_query($sql_str);
                if ($result !== true) return db_rollback();
                //更新需要回复的评论的作者的推送消息数
                $sql_str = "UPDATE `message_count` 
                                SET `Comment` = `Comment` + 1, `AllComment` = `AllComment` + 1
                                WHERE `UserId` = {$comment_msg->UserId}";
                $result = db_query($sql_str);
                if ($result !== true) return db_rollback();
                //if ($comment_msg->UserName != $at_username) //如果回复需要@的人不是回复的人
                //{
                if ($at_username != '') //需要@的人
                {
                    //获取@的人的id
                    $sql_str = "SELECT Id FROM users WHERE Name = '{$at_username}'";
                    $result = db_query($sql_str);
                    if ($result === false) return db_rollback();
                    if ($result->num_rows <= 0 ||
                        !($atuser_msg = $result->fetch_object())
                    ) //没有获得回复的对象
                    {
                        db_rollback();
                        return "错误:无法获取要回复人的id";
                    }
                    //推送消息到需要@的人
                    $sql_str = "INSERT INTO `message_comment` 
                                        SET `Type` = 5,`MsgIdFrom` = {$comment_id},`UserId`={$atuser_msg->Id}";
                    $result = db_query($sql_str);
                    if ($result !== true) return db_rollback();
                    //更新需要回复的评论的作者的推送消息数
                    $sql_str = "UPDATE `message_count` 
                                        SET `Comment` = `Comment` + 1, `AllComment` = `AllComment` + 1
                                        WHERE `UserId` = {$comment_msg->UserId}";
                    $result = db_query($sql_str);
                    if ($result !== true) return db_rollback();
                }
                //}
                //}
            }

            //更新作品的评论数、作者被评论的总数以及作者评论的推送消息数
            $result = db_query("UPDATE `users`,`works`,`message_count` 
                                SET `works`.`CommentCount` = {$comment_count} ,
                                    `users`.`CommentCount` = `users`.`CommentCount` + 1,
                                    `message_count`.`Comment` = `message_count`.`Comment` + 1,
                                    `message_count`.`AllComment` = `message_count`.`AllComment` + 1
                                WHERE `works`.`Id` = {$work_id} AND 
                                      `users`.`Id` = {$work_msg->Author} AND 
                                      `message_count`.`UserId` = {$work_msg->Author}");

            if ($result !== true) return db_rollback();
            $op = new user_operate();
            $result1 = $op->operate_save($op::WorkCommend, $_SESSION['user_id'], $comment_id);
            if ($result1 !== TRUE) {
                db_rollback();
                return $result1;
            }
            //评论信息插入成功 则插入热门统计表
            $result11 = db_query("INSERT INTO `works_hot_1` 
                                  SET `WorkId` = {$work_id},
                                      `OpType` = 2");
            if ($result !== true) return db_rollback();
            $result11 = db_query("INSERT INTO `works_hot_2` 
                                  SET `WorkId` = {$work_id},
                                      `OpType` = 2");
            if ($result !== true) return db_rollback();
            db_commit();
            return $comment_count;
        } else {
            return "错误:评论的文本不合法";
        }
    }

    /**
     * 评论点赞 成功返回1 取消点赞返回-1 错误返回错误信息
     * @param int 评论Id
     */
    function work_comment_up($comment_id)
    {
        if (!is_numeric($comment_id)) {
            return "错误:评论点赞信息提交错误";
        }
        $result = 1;
        $update_type = '+';
        db_begin();
        $result1 = db_query("INSERT INTO `works_comment_up` 
                             SET `CommentId` = '{$comment_id}',
                                 `UserId` = '{$_SESSION['user_id']}'");

        if ($result1 !== true) {
            if (db_errno() === 1062) //已经赞过 则取消点赞
            {
                $result = -1;
                $update_type = '-';
                $result2 = db_query("DELETE FROM `works_comment_up` 
                                     WHERE `CommentId` = '{$comment_id}' AND
                                           `UserId` = '{$_SESSION['user_id']}'");

                if ($result2 !== true) return db_rollback();
            } else {
                return db_rollback();
            }
        }
        //更新评论的点赞数
        $result3 = db_query("UPDATE `works_comment` 
                             SET `UpCount` = `UpCount` {$update_type} 1 
                             WHERE `Id` = {$comment_id}");
        if ($result3 !== true) return db_rollback();

        db_commit();
        return $result;
    }

    /**
     * 删除评论 成功返回'1' 失败返回错误信息
     * @param int $comment_id 评论Id
     * @param int $user_id 用户Id
     */
    function work_comment_dele($comment_id, $user_id)
    {
        if (!is_numeric($comment_id) || !is_numeric($user_id)) {
            return "作品评论删除时，提交的信息错误";
        }
        $check_ok = FALSE;
        $row;
        $result_sele1 = db_query("SELECT `works`.`Id`,
                                         `works`.`Author`,
                                         `works_comment`.`UserId`,
                                         `works_comment`.`CommentDt` 
                                  FROM `works`,`works_comment` 
                                  WHERE `works_comment`.`Id` = {$comment_id} AND 
                                        `works`.`Id` = `works_comment`.`WorkId`");
        if ($result_sele1 !== FALSE) {
            if ($row = $result_sele1->fetch_object()) {
                //作品作者和评论者可以删除
                if ($row->Author == $user_id || $row->UserId == $user_id) {
                    $check_ok = TRUE;
                }
            }
        }
        if ($_SESSION['user_level'] >= 90) { //如果为管理员可以删除
            $check_ok = TRUE;
        }
        if ($check_ok == TRUE) {
            db_begin();
            //删除评论 评论点赞、评论举报、作者的被推送的评论消息
            $result1 = db_query("DELETE FROM `works_comment`
			                     WHERE `works_comment`.`Id` = {$comment_id}");

            if ($result1 !== TRUE) return db_rollback();

            if (db_affected_rows() > 0) {
                //更新作品的评论数、作者被评论的总数
                $result2 = db_query("UPDATE `users`,`works` 
                                     SET `works`.`CommentCount` = `works`.`CommentCount` - 1,
	                                     `users`.`CommentCount` = `users`.`CommentCount` - 1 
	                                 WHERE `works`.`Id` = {$row->Id} AND 
	                                       `users`.`Id` = {$row->Author}");
                if ($result2 !== TRUE) return db_rollback();
            }
            //删除评论点赞、评论举报、作者的被推送的评论消息
            $result3 = db_query("DELETE FROM `works_comment_up` WHERE `CommentId` = {$comment_id}");
            $result4 = db_query("DELETE FROM `works_comment_report` WHERE `CommentId` = {$comment_id}");
            $result5 = db_query("DELETE FROM `message_comment` 
                                 WHERE `Type` = 1 AND `MsgIdFrom` = {$comment_id} AND 
                                       `UserId`={$row->Author}");
            if ($result3 !== TRUE || $result4 !== TRUE || $result5 !== TRUE) {
                return db_rollback();
            }

            $deleCount = db_affected_rows();
            if ($deleCount > 0) {
                $update_row = array();
                $update_row['UserId'] = $row->Author;
                $update_row['AllComment'] = "`AllComment` - {$deleCount}";
                $result6 = db_update('message_count', $update_row, 'UserId');
                if ($result6 !== TRUE) return db_rollback();
            }

            //删除掉评论时间正负1秒内的热门统计 Limit1
            $date = new DateTime($row->CommentDt);
            $i = DateInterval::createFromDateString('-1 seconds');
            $date->add($i);
            $sql_time1 = $date->format('Y-m-d H:i:s');
            $i = DateInterval::createFromDateString('+2 seconds');
            $date->add($i);
            $sql_time2 = $date->format('Y-m-d H:i:s');
            $result11 = db_query("DELETE FROM `works_hot_1` 
			                      WHERE `WorkId` = {$row->Id} AND 
			                            `OpType` = 2 AND 
			                            `OpDt` BETWEEN '{$sql_time1}' AND '{$sql_time2}' 
			                      LIMIT 1");
            if ($result11 !== TRUE) return db_rollback();
            $result11 = db_query("DELETE FROM `works_hot_2`
			                      WHERE `WorkId` = {$row->Id} AND 
			                            `OpType` = 2 AND 
			                            `OpDt` BETWEEN '{$sql_time1}' AND '{$sql_time2}'
			                      LIMIT 1");
            if ($result11 !== TRUE) return db_rollback();

            db_commit();
            return '1';
        } else {
            return '无权限删除此评论';
        }
    }

    /**
     * 保存作品 成功返回作品Id和附加信息 如果有附加信息与作品Id用|分隔 错误返回错误信息
     * @param object $data 提交的数据内容
     */
    function work_save(&$data)
    {
        if (!$_SESSION["user_level"]) {
            return "错误:请登录";
        } elseif (!isset($data["work_state"]) || ($data["work_state"] != 1 && $data["work_state"] != 0)) {
            return "错误:提交的作品状态不允许";
        } elseif (!isset($data['work_name']) || !isset($data['introd']) || !isset($data['type']) || !isset($data['stype']) || !isset($data['tags'])) {
            return "错误:提交的作品信息不完全";
        }
        $data['work_name'] = db_escape(urldecode($data['work_name']));
        $data['introd'] = db_escape(urldecode($data['introd']));
        $data['tags'] = db_escape(urldecode($data['tags']));
        $data['type'] = db_escape(urldecode($data['type']));
        $data['stype'] = db_escape(urldecode($data['stype']));
        $work_name_len = strlen($data['work_name']);
        if (strlen($data['releasedt']) == 16) {
            $data['releasedt'] .= ':00';
        }
        if ($work_name_len <= 4) {
            return "错误:提交的作品名长度小于4字符";
        } elseif ($work_name_len > 30) {
            return "错误:提交的作品名长度超过30字符";
        } elseif (mb_strlen($data['introd'], 'utf8') > 135) {
            return "错误:提交的作品介绍长度超过135字符";
        } elseif (mb_strlen($data['tags'], 'utf8') > 135) {
            return "错误:提交的作品标签字符长度超过135字符";
        } elseif (mb_strlen($data['type'], 'utf8') > 15) {
            return "错误:提交的作品类型字符长度超过15字符";
        } elseif (mb_strlen($data['stype'], 'utf8') > 15) {
            return "错误:提交的作品鞋款字符长度超过15字符";
        } elseif ($data['work_state'] != 0 && $data['work_state'] != 1) {
            return "错误:提交的作品状态不合法";
        } elseif (isset($data['releasedt']) && $data['releasedt'] != '' && !preg_match(work_m::PregDateTime, $data['releasedt'])) {
            return "错误:作品发布时间格式应为'2000-01-01'";
        }

        //20170111 添加 获取作品名+简介+鞋款+标签的分词
        //标签的词汇本身已用空格分好
        //获取的分词用空格分隔后 写入Keyword字段 用于搜索
        $keyText = "{$data['work_name']} {$data['introd']} {$data['stype']}";
        global $CfgPara;
        require_once("{$CfgPara->root}/class/keyword_zh.func.php");
        $keyWord = get_keywords($keyText);
        rtrim($keyWord, ' ');
        trim($data['tags'], ' ');
        $keyWord = "{$keyWord} {$data['tags']}";
        if (isset($data["work_id"]) && is_numeric($data['work_id']) && $data['work_id'] > 0) //更新
        {
            $result = $this->work_edit_update($data, $keyWord);
        } else //插入
        {
            $result = $this->work_edit_insert($data, $keyWord);
        }
        return $result;
    }

    /**
     * 作品编辑更新 正确返回作品id 错误返回错误信息
     */
    function work_edit_update(&$data, &$keyWord)
    {
        if (!is_numeric($data["work_id"])) {
            return "错误:提交的作品信息错误";
        }
        $work_msg = $this->work_msg($data["work_id"]);
        if (is_string($work_msg) || $work_msg === false) //查询错误
        {
            return "错误:无法查询到该作品";
        }

        if ($_SESSION["user_level"] < 90) //当前用户非管理员
        {
            if ($work_msg->Author != $_SESSION["user_id"]) {
                return "错误:无权限管理此作品";
            }
        }
        //20161121 修改 保存草稿时可以不需要图片
        if ($data["work_state"] == 1 && strlen($data["work_img_names"]) <= 0) {
            return "错误:作品尚未提交图片";
        }
        global $CfgPara;
        $imgs = do_edit_img(3, $data["work_img_names"],
            "{$CfgPara->root}/works_pic/", 'works', 'Picture', (int)$data['work_id']);
        if ($imgs === false) {
            return "错误:作品的图片处理发生错误";
        }
        db_begin();
        $sql_str = "UPDATE `works` 
                    SET 
                    `Name`='{$data['work_name']}',
                    `Author` = '{$_SESSION['user_id']}',
                    `Picture` = '{$imgs}',
                    `Introd`='{$data['introd']}',
                    `Type`='{$data['type']}',
                    `SType`='{$data['stype']}',
                    `Tags`='{$data['tags']}',
                    `State`='{$data['work_state']}', 
                    `Keyword` = '{$keyWord}'";
        if (isset($data['releasedt']) && $data['releasedt'] != "") {
            $sql_str .= ",`ReleaseDt`='{$data['releasedt']}'";
        }
        $sql_str .= " WHERE `Id` = '{$data['work_id']}'";

        $result = db_query($sql_str);
        if ($result === false) {
            if (db_errno() === 1062) //20170204 添加 检查当前作品名是否已经存在
            {
                db_rollback();
                return '当前作品名已存在';
            }
            db_rollback();
        }

        //更新用户作品数量 如果先前的状态为已发布 更新后状态为草稿 则增加草稿数 减少发布数
        if ($work_msg->State == 1 && $data['work_state'] == 0) {
            $fname[0] = 'WorksCount';
            $fname[1] = 'WorksDraftCount';
            $state_change = 1; //状态将会改变 需要将作者的发布作品数与草稿作品数更新
        } // 如果先前的状态为草稿 更新后状态为发布 则增加发布数 减少草稿数
        elseif ($work_msg->State == 0 && $data['work_state'] == 1) {
            $fname[0] = 'WorksDraftCount';
            $fname[1] = 'WorksCount';
            $state_change = 1; //状态将会改变 需要将作者的发布作品数与草稿作品数更新
            if (!isset ($_SESSION['user_id'])) return '发布作品前，请登陆';
        }
        if (isset($fname) && isset($state_change) && $state_change == 1) {
            $sql_str = "UPDATE `users` 
                        SET `{$fname[1]}` = `{$fname[1]}` + 1 , `{$fname[0]}` = `{$fname[0]}` - 1
                        WHERE `Id` = {$_SESSION['user_id']}";
            $result2 = db_query($sql_str);
            if ($result2 === false) {
                return db_rollback();
            }
        }

        if (isset($state_change) && $state_change == 1 && $data['work_state'] == 1) {
            $op = new user_operate();
            $result1 = $op->operate_save(user_operate::WorkRelease, $_SESSION['user_id'], $data['work_id']);
            if ($result1 !== TRUE) {
                db_rollback();
                return $result1;
            }
        }
        // 提交事务
        db_commit();
        return $data['work_id'];
    }

    /**
     * 获取作品信息 正确返回对象，错误返回错误信息
     */
    public function work_msg($work_id)
    {
        if (!is_numeric($work_id)) {
            return "错误:提交的作品信息错误";
        }
        $sql_str = "SELECT `works`.*,date_format(`works`.`ReleaseDt`,'%Y.%m.%d') as ReleaseDate,
                    `users`.Name as UserName,`users`.Avatar as UserAvatar,`users`.`WorksCount` as UserWorkCount 
                    FROM `works`,`users`
                    WHERE `works`.`Id` = '{$work_id}' AND `works`.`Author` = `users`.`Id`";
        $result = db_query($sql_str);
        if ($result instanceof mysqli_result) {
            if (db_fetch_object($result, $row) === 1)
                return $row;
            else return "错误:未查询到相关作品信息";
        } else {
            return db_error();
        }
    }

    /**
     * 新建作品 正确返回作品id 错误返回错误信息
     */
    function work_edit_insert(&$data, &$keyWord)
    {
        // 20170405 新增 发布作品需要余额2元 如果在界面时选择的是第三方支付工具 
        // 例如微信、支付宝 在此函数前已经将钱加入余额中
        if (!isset ($_SESSION['user_id'])) return '发布作品前，请登陆';
        global $CfgPara;

        db_begin();
        //20161121 修改 保存草稿时可以不需要图片
        if ($data["work_state"] == 1 && strlen($data["work_img_names"]) <= 0) {
            return "错误:作品尚未提交图片";
        }
        $imgs = do_edit_img(3, $data["work_img_names"],
            "{$CfgPara->root}/works_pic/", 'works', 'Picture');
        if ($imgs === false) return '处理作品图片时发生错误';
        $sql_str = "INSERT INTO `works` 
                    SET `Author` = '{$_SESSION['user_id']}',
                        `Picture` = '{$imgs}',
                        `Name`='{$data['work_name']}',
                        `Introd`='{$data['introd']}',
                        `Type`='{$data['type']}',
                        `SType`='{$data['stype']}',
                        `Tags`='{$data['tags']}',
                        `State`='{$data['work_state']}', 
                        `Keyword`='{$keyWord}'";
        if (isset($data['releasedt']) && $data['releasedt'] != "") {
            $sql_str .= ",`ReleaseDt`='{$data['releasedt']}'";
        }

        $result = db_query($sql_str);
        if ($result === false) {
            if (db_errno() === 1062) //20170204 添加 检查当前作品名是否已经存在
            {
                db_rollback();
                return '当前作品名已存在';
            }
            db_rollback();
        }
        $work_id = db_insert_id();
        // 更新用户作品数量
        if ($data['work_state'] == 1) $fname = 'WorksCount';
        else $fname = 'WorksDraftCount';
        $sql_str = "UPDATE `users` SET `{$fname}` = `{$fname}` + 1 WHERE `Id` = {$_SESSION['user_id']}";
        $result2 = db_query($sql_str);
        if ($result2 === false) return db_rollback();

        if ($data['work_state'] == 1) {
            $op = new user_operate();
            $result1 = $op->operate_save($op::WorkRelease, $_SESSION['user_id'], $work_id);
            if ($result1 !== TRUE) {
                db_rollback();
                return $result1;
            }
        }
        db_commit();
        return $work_id;
    }

    /**
     * 作品发布 将原为草稿的作品直接发布 其它都不修改 成功返回1 如果原本已发布返回0 失败返回错误信息
     * @param int $work_id 作品id
     * @param string $order_id 订单号
     * @param CPay $pay 支付操作类
     */
    function work_edit_release($work_id, &$order_id, &$pay)
    {
        if (!is_numeric($work_id)) {
            return "作品发布时，提交的作品信息错误";
        }
        if (!isset($order_id)) {
            return "作品发布时，提交的订单号错误";
        }
        $work_msg = $this->work_msg($work_id);
        if (is_string($work_msg) || $work_msg === false) //查询错误
        {
            return "作品发布时，无法查询到该作品";
        }
        if ($work_msg->State == 1) // 原作品状态已为1 已经发布
        {
            return 0;
        }
        // db_begin(); 20171119 此处事务由上层调用者管理
        $sql_str = "UPDATE `works` 
                    SET `State`='1' 
                    WHERE `Id` = {$work_id}";
        $result = db_query($sql_str);
        if ($result === false) {
            return db_error();
        }
        $sql_str = "UPDATE `users` 
                    SET `WorksCount` = `WorksCount` + 1 , 
                        `WorksDraftCount` = `WorksDraftCount` - 1
                    WHERE `Id` = {$_SESSION['user_id']}";
        $result = db_query($sql_str);
        if ($result === false) {
            return db_error();
        }
        // 插入消费记录
        $result = $pay->consume_insert(CPay::ConsumeType_WorkRelease, CPay::GoodsPrice_WorkRelease, $order_id);
        if ($result != 1) {
            return $result;
        }

        // 消费数据统计更新
        $result = $pay->consume_count_record(CPay::GoodsPrice_WorkRelease, CPay::ConsumeType_WorkRelease);
        if ($result !== 1) return db_error();
        $op = new user_operate();
        $result = $op->operate_save(user_operate::WorkRelease, $_SESSION['user_id'], $work_id);
        if ($result !== TRUE) {
            return $result;
        }
        // db_commit(); 20171119 此处事务由上层调用者管理
        return 1;
    }

    /**
     * 删除作品 成功返回'1' 失败返回错误信息
     * @param int $work_id 作品Id
     * @param string $root 作品图片的路径最后含'/'
     */
    function work_dele($work_id, $root)
    {
        if (!is_numeric($work_id)) {
            return "作品删除时，提交的作品信息错误";
        }
        //检查当前用户是否为管理员
        if (!isset($_SESSION['user_level']) || $_SESSION['user_level'] < 90 ||
            !isset($_SESSION['user_admin']) || $_SESSION['user_admin'] != 1
        ) {
            return '无权限删除作品';
        }

        db_begin();
        //获取本作品信息
        $result = db_query("SELECT * FROM `works` WHERE `Id` = {$work_id} FOR UPDATE");
        if ($result !== FALSE) {
            if ($result->num_rows > 0 && $workMsg = $result->fetch_object()) {

            } else {
                return '未查询到要删除的作品';
            }
        } else {
            return db_rollback();
        }
        //删除掉作品
        $result_dele = db_query("DELETE FROM `works` WHERE `Id` = {$work_id}");
        if ($result_dele === FALSE) {
            return db_rollback();
        }
        if (db_affected_rows() <= 0) {
            return '未找到要删除的作品';
        }
        //查询当前用户的本领  WorksId为逗号分隔的作品Id
        $result = db_query("SELECT `user_field_works`.`FieldId`, `user_field_works`.`WorksId`
                            FROM `user_field`,`user_field_works` 
                            WHERE `user_field`.`UserId` = {$workMsg->Author} AND 
                                  `user_field_works`.`FieldId` = `user_field`.`Id` AND 
                                  FIND_IN_SET('{$work_id}', `WorksId`);");

        if ($result !== FALSE) {
            while ($row = $result->fetch_object()) {
                //删除用户本领中的作品
                $fieldWorkIds = explode(',', rtrim($row->WorksId, ','));
                $fieldIdString = '';
                $hasWorkId = FALSE;
                foreach ($fieldWorkIds as $fieldWorkId) {
                    if ($fieldWorkId != $work_id) {
                        $fieldIdString .= $fieldWorkId . ',';
                    } else {
                        $hasWorkId = TRUE;
                    }
                }
                if ($hasWorkId === TRUE) {
                    $result_field = db_query("UPDATE `user_field_works` 
                                              SET `WorksId` = '{$fieldIdString}' 
                                              WHERE `FieldId` = {$row->FieldId}");
                    if ($result_field === FALSE) {
                        return db_rollback();
                    }
                }
            }
        } else {
            return db_rollback();
        }
        //查找本作品下的评论
        $result = db_query("SELECT `Id` FROM `works_comment` WHERE `WorkId` = {$work_id}");
        if ($result !== FALSE) {
            while ($row = $result->fetch_object()) {
                //删除作品作者的评论推送消息
                $result_dele = db_query("DELETE FROM `message_comment` 
                                         WHERE `Type` = 1 AND `MsgIdFrom` = {$row->Id} AND 
                                               `UserId`={$workMsg->Author}");
                if ($result_dele === FALSE) return db_rollback();
                $deleCount = db_affected_rows();
                if ($deleCount > 0) {
                    $update_row = array();
                    $update_row['UserId'] = $workMsg->Author;
                    $update_row['AllComment'] = "`AllComment` - {$deleCount}";
                    $result6 = db_update('message_count', $update_row, 'UserId');
                    if ($result6 !== TRUE) return db_rollback();
                }

                //删除评论的点赞
                $result_dele = db_query("DELETE FROM `works_comment_up` 
                                         WHERE `CommentId` = {$row->Id}");
                if ($result_dele === FALSE) return db_rollback();
                //删除评论的举报
                $result_dele = db_query("DELETE FROM `works_comment_report` 
                                         WHERE `CommentId` = {$row->Id}");
                if ($result_dele === FALSE) return db_rollback();
            }
        } else {
            return db_rollback();
        }
        //删除本作品下的评论
        $result_dele = db_query("DELETE FROM `works_comment` 
                                 WHERE `WorkId` = {$work_id}");
        if ($result_dele === FALSE) return db_rollback();

        //删除作品的操作信息 用户对此作品的操作消息 例如评论、推荐 将在用户查看动态时如果查询不到相应记录则删除

        //删除用户的收藏
        $result_dele = db_query("DELETE FROM `user_collect` 
                                 WHERE `Type` = 0 AND `CollectId` = {$work_id}");
        if ($result_dele === FALSE) return db_rollback();

        //删除作品举报
        $result_dele = db_query("DELETE FROM `works_report` 
                                 WHERE `WorkId` = {$work_id}");
        if ($result_dele === FALSE) return db_rollback();

        //删除作品推荐
        $result_dele = db_query("DELETE FROM `works_up` 
                                 WHERE `WorkId` = {$work_id}");
        if ($result_dele === FALSE) return db_rollback();

        //查询作品是否在专题下 确定是否已审核
        $result = db_query("SELECT `TopicId`,`State` FROM topic_works 
		                              WHERE `WorkId` = {$work_id} FOR UPDATE");
        //更新专题下的作品数量
        if ($result !== FALSE) {
            while ($row = $result->fetch_object()) {
                //如果专题已审核 专题下已审核作品1 否则 待审核作品0  -1（已拒绝的） 
                if ($row->State == 1) {
                    //已审核
                    $fieldName = 'WorksCount';
                } elseif ($row->State == 0) {
                    $fieldName = 'WaitCheckCount';
                }
                if (isset($fieldName)) {
                    $result_update = db_query("UPDATE `topic` 
                                               SET `{$fieldName}` = `{$fieldName}` - 1 
                                               WHERE `Id` = {$row->TopicId}");
                    if ($result_update === FALSE) return db_rollback();
                }
            }
        } else {
            return db_rollback();;
        }
        //删除专题下的作品记录
        $result_dele = db_query("DELETE FROM `topic_works` 
                                 WHERE `WorkId` = {$work_id}");
        if ($result_dele === FALSE) return db_rollback();

        //删除提醒审核通过的提醒消息
        $result_dele = db_query("DELETE FROM `message_remind` 
                                 WHERE `Type` = 1 AND `MsgIdFrom` = {$work_id} AND 
                                       `UserId` = {$workMsg->Author}");
        if ($result_dele === FALSE) return db_rollback();
        // 更新被删除的提醒消息数量
        $deleCount = db_affected_rows();
        $sql_str = "UPDATE `message_remind` 
                    SET `AllRemind` = `AllRemind` - {$deleCount}";
        $result_dele = db_query($sql_str);
        if ($result_dele === FALSE) return db_rollback();

        //更新用户的作品数
        if ($workMsg->State == 1) { //如果作品的状态为已发布
            $fieldName = 'WorksCount';
        } else { //草稿的数量
            $fieldName = 'WorksDraftCount';
        }
        $result_update = db_query("UPDATE `users` 
                                    SET `{$fieldName}` = `{$fieldName}` - 1 
                                    WHERE `Id` = {$workMsg->Author}");
        if ($result_update === FALSE) {
            return db_rollback();
        }
        //删除作品涉及到的图片
        $workImgs = explode(';', rtrim($workMsg->Picture, ';'));
        foreach ($workImgs as $workImg) {
            $fileName = $root . make_img_name::make_img_mini_name($workImg);
            if (file_exists($fileName)) {
                @unlink($fileName);
            }
            $fileName = $root . make_img_name::make_img_micro_name($workImg);
            if (file_exists($fileName)) {
                @unlink($fileName);
            }
            $fileName = $root . make_img_name::make_img_old_name($workImg);
            if (file_exists($fileName)) {
                @unlink($fileName);
            }
            $fileName = $root . $workImg;
            if (file_exists($fileName)) {
                @unlink($fileName);
            }
        }
        //以上操作全部正常
        db_commit();
        return 1;
    }

    /**
     * 作品主页浏览数计数 正确返回true 错误返回错误信息
     * @param int $work_id
     * @return bool|string
     */
    function work_show_view_count($work_id)
    {
        if (!is_numeric($work_id)) {
            return '错误: 提交的作品主页信息不正确';
        }
        //更新作品下的浏览次数
        /*20161215 修改 Human
         *仅作品发布后，才更新计数和插入热门表
         */
        $result = db_query(
            "UPDATE `works` SET `works`.`ViewCount` = `works`.`ViewCount` + 1 
             WHERE `works`.`Id` = {$work_id} AND `works`.`State` = 1");
        if ($result !== TRUE) {
            return db_rollback();
        }
        if (db_affected_rows() > 0) {
            //插入热门表 的浏览操作 由于热门表为MyISAM引擎 不能使用事务处理
            $result = db_query("INSERT INTO `works_hot_1`
                                          SET `WorkId` = {$work_id},
                                              `OpType` = 3");
            $result = db_query("INSERT INTO `works_hot_2`
                                          SET `WorkId` = {$work_id},
                                              `OpType` = 3");
        }

        return true;
    }

    /**
     * 检测当前用户是否已对评论点赞
     * @param int $comment_id
     * @return bool|string
     */
    function comment_up_check($comment_id)
    {
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return false;
        }
        if (!is_numeric($comment_id)) {
            return "检查评论是否已赞时:提交的信息错误";
        }
        $result = db_query("SELECT `CommentId` FROM `works_comment_up` WHERE `CommentId` = {$comment_id} AND `UserId` = {$_SESSION['user_id']}");
        if ($result !== false && $result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检测当前用户是否已参与作品的推荐 错误时提示错误信息
     * @param int $work_id
     * @return bool|string
     */
    function work_recommend_check($work_id)
    {
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return false;
        }
        if (!is_numeric($work_id)) {
            return "检查是否已推荐时:提交的信息错误";
        }
        $result = db_query("SELECT `WorkId` FROM `works_up` WHERE `WorkId` = {$work_id} AND `UserId` = {$_SESSION['user_id']} LIMIT 1");
        if ($result !== false && $result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检测当前用户是否已参与作品的评论 错误时提示错误信息
     * @param int $work_id
     * @return bool|string
     */
    function work_comment_check($work_id)
    {
        if (!isset($_SESSION['user_id']) || !is_numeric($_SESSION['user_id'])) {
            return false;
        }
        if (!is_numeric($work_id)) {
            return "检查是否已评论时:提交的信息错误";
        }
        $result = db_query("SELECT `WorkId` FROM `works_comment` WHERE `WorkId` = {$work_id} AND `UserId` = {$_SESSION['user_id']} LIMIT 1");
        if ($result !== false && $result->num_rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查作品列表的所有作品是否加入专题
     * 正确返回按作品列表顺序的数组 0待审核 1审核通过 -1审核被拒绝 -2未加入专题
     * 错误返回错误信息
     * @param array $work_msg_list 作品对象列表
     * @param int $topic_id 专题id
     * @return array|string
     */
    function work_add_topic_check($work_msg_list, $topic_id)
    {
        if (!is_numeric($topic_id)) return '作品检查是否加入专题时，提交的信息错误';
        //遍历作品列表 组成查询语句
        $sql_str = '';
        foreach ($work_msg_list as $work_msg) {
            $sql_str .= "SELECT Count(1) as WorkCheck, `topic_works`.`State` FROM `topic_works` WHERE `TopicId` = {$topic_id} AND `WorkId` = {$work_msg->Id} UNION ALL ";
        }
        $sql_str = substr($sql_str, 0, strlen($sql_str) - 10); //查询语句删除掉最后的'UNION ALL '
        //echo $sql_str;
        if ($sql_str == '') return array();
        $result = db_query($sql_str);
        if ($result !== false) {
            $i = 0;
            $rows = array();
            while ($row = $result->fetch_object()) {
                if (isset($row->State)) { //0待审核 1审核通过 -1审核被拒绝
                    $rows[$i] = $row->State;
                } else {
                    $rows[$i] = -2; //最后状态 -2可投稿 -1审核被拒绝 0待审核 1审核通过
                }
                $i++;
            }
            return $rows;
        } else {
            return db_error();
        }
    }

    /**
     * 获取来自各个专题的推荐数量的列表
     * 成功返回对象数组 失败返回错误信息
     * @param int $work_id 作品Id
     */
    function work_recommend_from_topic_list($work_id)
    {
        if (!is_numeric($work_id)) {
            return '获取各专题的推荐数时，作品信息错误';
        }
        $sql_str = "SELECT `topic`.`Picture`, `topic`.`Name`, 
		                   `works_up_topic`.`TopicId`,`works_up_topic`.`UpCount`
		            FROM `topic`,`works_up_topic` 
		            WHERE `works_up_topic`.`WorkId` = {$work_id} AND 
		                  `topic`.`Id` = `works_up_topic`.`TopicId`";
        $result = db_query($sql_str);
        if ($result !== FALSE) {
            if ($result->num_rows > 0) {
                $fetch_result = db_fetch_list($result, $rows);
                return $rows;
            } else {
                return '无相关作品的专题推荐信息';
            }
        } else {
            return db_errno();
        }
    }

    /**
     * 获取最新发布的鞋款列表
     * 成功返回字符串数组 失败返回错误信息
     */
    function hot_shoe_style_list()
    {
        $sql_str = "SELECT distinct(`SType`) FROM sneaker.works WHERE `SType` != '' ORDER BY `ReleaseDt` DESC LIMIT 10;";
        $result = db_query($sql_str);
        if ($result !== FALSE) {
            if ($result->num_rows > 0) {
                $rows = array();
                while ($row = $result->fetch_object()) {
                    $rows[] = $row->SType;
                }
                return $rows;
            } else {
                return '暂无热门鞋款推荐';
            }
        } else {
            return db_error();
        }
    }
}